package com.tengjunjie.qianqianaccountbook.qianqianaccountbook.controller;

import com.tengjunjie.qianqianaccountbook.qianqianaccountbook.VO.ResultVO;
import com.tengjunjie.qianqianaccountbook.qianqianaccountbook.converter.UserFormToUserDTOConverter;
import com.tengjunjie.qianqianaccountbook.qianqianaccountbook.entity.UserEntity;
import com.tengjunjie.qianqianaccountbook.qianqianaccountbook.enums.ResultEnum;
import com.tengjunjie.qianqianaccountbook.qianqianaccountbook.exception.AccountBookException;
import com.tengjunjie.qianqianaccountbook.qianqianaccountbook.form.UserForm;
import com.tengjunjie.qianqianaccountbook.qianqianaccountbook.service.UserService;
import com.tengjunjie.qianqianaccountbook.qianqianaccountbook.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by tengjunjie on 2017/12/3.
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserInfoController {
    @Autowired
    private UserService userService;

    //创建用户
    @PostMapping("/addUserInfo")
    public ResultVO<Map<String, String>> create(@Valid UserForm userForm,
                                                BindingResult bindingResult) {
        Map<String, String> map = new HashMap<>();
        try{
            //参数格式校验
            if (bindingResult.hasErrors()) {
                log.error("【创建用户】参数不正确, userForm={}", userForm);
                throw new AccountBookException(ResultEnum.PARAM_ERROR.getCode(),
                        bindingResult.getFieldError().getDefaultMessage());
            }
            //数据转换
            UserEntity userEntity = UserFormToUserDTOConverter.convert(userForm);
            int createResult = userService.createUser(userEntity);

            map.put("successTotal", String.valueOf(createResult));
        }catch(Exception ex){
            log.error(ex.getMessage());
            return ResultVOUtil.error(0,ex.getMessage());

        }

        //返回数据
        return ResultVOUtil.success(map);

    }

}
